package net.chenpu.gae.proxy;

import javax.servlet.http.Cookie;

public class CookieParser {
	public static final String VERSION = "version";
	public static final String COMMENT = "comment";
	public static final String DOMAIN = "domain";
	public static final String PATH = "path";
	public static final String EXPIRES = "expires";
	public static final String MAX_AGE = "Max-Age";
	public static final String SECURE = "Secure";
	public static final String HTTPONLY = "HttpOnly";

	public static Cookie parserOne(String cookieStr) {
		String key = null;
		String value = null;
		String comment = null;
		String domain = null;
		String version = null;
		String path = null;
		String expires = null;
		String maxAge = null;
		boolean secure = false;
		boolean httpOnly = false;
		String[] cArray = cookieStr.split(";");
		for (String s : cArray) {
			s = s.trim();
			int i1 = s.indexOf('=');
			if (i1 != -1) {
				String k = s.substring(0, i1).trim();
				String v = s.substring(i1 + 1).trim();
				if (k.equalsIgnoreCase(VERSION)) {
					version = v;
				} else if (k.equalsIgnoreCase(COMMENT)) {
					comment = v;
				} else if (k.equalsIgnoreCase(DOMAIN)) {
					domain = v;
				} else if (k.equalsIgnoreCase(PATH)) {
					path = v;
				} else if (k.equalsIgnoreCase(MAX_AGE)) {
					maxAge = v;
				} else if(k.equalsIgnoreCase(EXPIRES)){
					continue;
				}
				else {
					key = k;
					value = v;
				}
			} else {
				if (s.equalsIgnoreCase(SECURE)) {
					secure = true;
				} else if (s.equalsIgnoreCase(HTTPONLY)) {
					httpOnly = true;
				}
			}

		}
		Cookie cookie = new Cookie(key, value);
		if(comment != null){
			cookie.setComment(comment);
		}
		if(domain != null){
			cookie.setDomain(domain);
		}
		if(path != null){
			cookie.setPath(path);
		}
		if(version != null){
			cookie.setVersion(Integer.parseInt(version));
		}
		if(maxAge != null){
			cookie.setMaxAge(Integer.parseInt(maxAge));
		}
		if(secure){
			cookie.setSecure(true);
		}
		
		return cookie;
	}

	
	public static void main(String[] args) {
		String test = "_javaeye3_session_=BAh7BiIKZmxhc2hJQzonQWN0aW9uQ29udHJvbGxlcjo6Rmxhc2g6OkZsYXNoSGFzaHsABjoKQHVzZWR7AA%3D%3D--d983012383f33595e8b4015c6235ad6e21fa81cf; domain=javaeye.com; path=/; HttpOnly";
		Cookie cookie = parserOne(test);
		System.out.println(cookie);
	}
}
